package com.huafv.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huafv.reggie.common.R;
import com.huafv.reggie.entity.Category;
import com.huafv.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Resource
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category 分类实体
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category: {}", category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页查询分类
     * @param page 页数
     * @param pageSize 页大小
     */
    @GetMapping("/page")
    public R<Page<Category>> page(int page, int pageSize){
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Category::getSort);
        categoryService.page(categoryPage, lambdaQueryWrapper);
        return R.success(categoryPage);
    }

    /**
     * 删除分类
     * @param ids 分类Id
     */
    @DeleteMapping
    public R<String > delete(Long ids){
        log.info("删除分类 id : {}", ids);
//        categoryService.removeById(ids);
        categoryService.remove(ids);


        return R.success("分类信息删除成功");
    }

    /**
     * 修改分类
     * @param category 分类实体
     */
    @PutMapping
    public R<String> update(@RequestBody  Category category){
        log.info("编辑分类 Category : {}", category);
        categoryService.updateById(category);
        return R.success("编辑分类成功");
    }

    /**
     * 根据条件分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        // 构造条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 添加条件
        lambdaQueryWrapper.eq(category.getType() != null, Category::getType,category.getType());
        // 添加排序条件
        lambdaQueryWrapper.orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
        // 查询
        List<Category> list = categoryService.list(lambdaQueryWrapper);

        return R.success(list);
    }
}
